import QtQuick 2.12
import QtQuick.Layouts 1.12
import QtQuick.Controls 2.12
import QtGraphicalEffects 1.12
import "../gis" as Gis

/**
 * @brief GIS地图页面 - 全屏地图显示，集成路线规划功能
 * 
 * 根据YCLocation技术文档实现：
 * - 使用Qt Location插件系统加载地图瓦片
 * - 集成路线规划功能（RouteService）
 * - 全屏地图显示，浮动控制面板
 * - Canvas绘制路径和站点
 */
Rectangle {
    id: gisPage
    color: "#f0f0f0"
    
    // ==================== 属性定义 ====================
    
    property real currentLon: 109.240150
    property real currentLat: 23.724696
    property bool mapReady: false
    property bool mapLoading: true
    
    // 路线规划状态
    property bool isPlanning: false
    property string routeProvider: "direct"  // direct, openroute, google, bing
    property double routeDistance: 0.0  // 路径总距离（米）
    property double routeDuration: 0.0  // 路径预计时长（秒）
    
    // 保存的路径列表（用于直线规划选择下拉框）
    property var savedPathsModel: [
        {text: "直线规划", value: "direct"},
        {text: "OpenRouteService", value: "openroute"},
        {text: "Google Directions", value: "google"},
        {text: "Bing Maps", value: "bing"}
    ]
    
    // 保存的路径数据（存储路径点信息）
    // 使用QtObject来存储动态数据，避免QML property的限制
    QtObject {
        id: savedPathsDataStorage
        property var data: ({})
        
        function setPathData(key, value) {
            var obj = data
            if (!obj) {
                obj = {}
            }
            obj[key] = value
            data = obj
        }
        
        function getPathData(key) {
            var obj = data
            if (!obj) {
                return null
            }
            return obj[key]
        }
    }
    
    // 当前选择的地图类型
    property int selectedMapType: 0  // 0: 高德地图(在线), 1: 离线地图
    
    // 路径编辑模式状态（避免直接访问map对象）
    property bool pathEditMode: false
    property bool fieldPlanMode: false  // 农田规划模式状态
    
    // ==================== 主地图容器（全屏） ====================
    
    Item {
        id: mapContainer
        anchors.fill: parent
        
        // 高德地图（Qt Location + YCLocationProvider插件）
        Loader {
            id: gaodeMapLoader
            anchors.fill: parent
            visible: selectedMapType === 0
            active: visible  // 只在可见时加载
            source: "qrc:/gis/TiledMapViewerGaode.qml"
            
            property real initialLon: currentLon
            property real initialLat: currentLat
            
            onLoaded: {
                console.log("高德地图组件已加载")
                
                // 设置初始中心位置
                if (item) {
                    item.centerLon = initialLon
                    item.centerLat = initialLat
                    item.zoomLevel = 16
                    
                    // 连接信号
                    if (item.mapReady) {
                        item.mapReady.connect(function() {
                            console.log("✅ 高德地图准备就绪")
                            mapLoading = false
                            mapReady = true
                        })
                    } else {
                        // 如果信号不存在，直接设置mapReady
                        console.log("⚠️ mapReady信号不存在，直接设置状态")
                        mapLoading = false
                        mapReady = true
                    }
                    
                    item.locationChanged.connect(function(lon, lat) {
                        currentLon = lon
                        currentLat = lat
                    })
                    
                    item.mapClicked.connect(function(lon, lat) {
                        console.log("地图点击:", lon.toFixed(8), lat.toFixed(8))
                    })
                    
                    item.pathChanged.connect(function() {
                        console.log("路径已更改，路径点数:", item.pathPointsModel.count)
                        // 路径点变化时自动计算距离
                        updatePathDistance()
                    })
                }
            }
            
            onStatusChanged: {
                if (status === Loader.Error) {
                    console.error("高德地图加载失败！")
                }
            }
        }
        
        // 离线地图（静态PNG）
        Gis.OfflineMapViewer {
            id: offlineMap
            anchors.fill: parent
            visible: selectedMapType === 1
            
            onMapReady: {
                console.log("离线地图准备就绪")
                mapLoading = false
                mapReady = true
                
                // 强制刷新按钮状态
                Qt.callLater(function() {
                    console.log("🔄 强制刷新按钮状态")
                    debugButtonStatus()
                })
            }
            
            onLocationChanged: function(lon, lat) {
                currentLon = lon
                currentLat = lat
            }
            
            onMapClicked: function(lon, lat) {
                console.log("地图点击:", lon.toFixed(8), lat.toFixed(8))
            }
            
            onPathChanged: {
                console.log("路径已更改，路径点数:", offlineMap.pathPointsModel.count)
                // 路径点变化时自动计算距离
                updatePathDistance()
            }
        }
    }
    
    // ==================== 浮动控制面板（左侧，可折叠） ====================
    
    property bool panelExpanded: false  // 控制面板展开状态
    
    // 折叠按钮（默认可见）
    Rectangle {
        id: toggleButton
        anchors.left: parent.left
        anchors.top: parent.top
        anchors.margins: 10
        width: 24
        height: 24
        color: "#2196f3"
        radius: 8
        opacity: 0.95
        z: 180
        
        layer.enabled: true
        layer.effect: DropShadow {
            horizontalOffset: 0
            verticalOffset: 2
            radius: 12
            samples: 24
            color: "#40000000"
        }
        
        Text {
            anchors.centerIn: parent
            text: panelExpanded ? "◀" : "🗺️"
            font.pixelSize: panelExpanded ? 20 : 24
            color: "white"
            font.bold: true
        }
        
        MouseArea {
            anchors.fill: parent
            onClicked: {
                panelExpanded = !panelExpanded
            }
        }
    }
    
    // 控制面板（可折叠，半透明）
    Rectangle {
        id: leftControlPanel
        anchors.left: parent.left
        anchors.top: parent.top
        anchors.bottom: parent.bottom
        anchors.margins: 10
        width: 240
        color: "#e8ffffff"  // 半透明白色
        radius: 8
        opacity: 0.95
        z: 100
        
        // 折叠动画
        visible: panelExpanded
        x: panelExpanded ? 0 : -260
        
        Behavior on x {
            NumberAnimation { duration: 300; easing.type: Easing.OutQuad }
        }
        
        layer.enabled: true
        layer.effect: DropShadow {
            horizontalOffset: 0
            verticalOffset: 2
            radius: 12
            samples: 24
            color: "#40000000"
        }
        
        ScrollView {
            anchors.fill: parent
            anchors.margins: 16
            clip: true
            
            ScrollBar.vertical.policy: ScrollBar.AsNeeded
            
            ColumnLayout {
                width: leftControlPanel.width - 32  // 减去左右边距
                spacing: 12
                
                // 面板标题（带折叠按钮）
                RowLayout {
                    Layout.fillWidth: true
                    spacing: 8

                    Text {
                        text: "🗺️"
                        font.pixelSize: 24
                    }
                    
                    Label {
                        text: "路径规划控制"
                        font.pixelSize: 16
                        font.bold: true
                        color: "#2c3e50"
                        Layout.fillWidth: true
                    }
                    
                    // 折叠图标按钮
                    Rectangle {
                        width: 14
                        height: 14
                        color: "transparent"
                        
                        Text {
                            anchors.centerIn: parent
                            text: "✕"
                            font.pixelSize: 18
                            color: "#7f8c8d"
                        }
                        
                        MouseArea {
                            anchors.fill: parent
                            onClicked: {
                                panelExpanded = false
                            }
                        }
                    }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 1
                    color: "#e0e0e0"
                }
                
                // 地图类型切换
                ColumnLayout {
                    spacing: 8
                    Layout.fillWidth: true
                    
                    Label {
                        text: "地图类型"
                        font.pixelSize: 13
                        font.bold: true
                        color: "#34495e"
                    }
                    
                    // 地图类型切换按钮（横向排列）
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 8
                        Button {
                            text: "高德地图 ✓"
                            checked: selectedMapType === 0
                            checkable: false
                            Layout.fillWidth: true
                            Layout.preferredHeight: 30
                            
                            background: Rectangle {
                                color: selectedMapType === 0 ? "#2196f3" : "#f0f0f0"
                                radius: 4
                                border.color: "#2196f3"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: selectedMapType === 0 ? "white" : "#2196f3"
                                font.pixelSize: 12
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter

                            }
                            
                            onClicked: {
                                selectedMapType = 0
                                console.log("切换到高德地图 (YCLocationProvider)")
                                // 延迟调试按钮状态
                                Qt.callLater(function() {
                                    debugButtonStatus()
                                })
                            }
                        }
                        
                        Button {
                            text: "工作区"
                            checked: selectedMapType === 1
                            checkable: false
                            Layout.fillWidth: true
                            Layout.preferredHeight: 30
                            
                            background: Rectangle {
                                color: selectedMapType === 1 ? "#2196f3" : "#f0f0f0"
                                radius: 4
                                border.color: "#2196f3"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: selectedMapType === 1 ? "white" : "#2196f3"
                                font.pixelSize: 12
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                selectedMapType = 1
                                console.log("切换到离线地图 (工作区)")
                                // 延迟调试按钮状态
                                Qt.callLater(function() {
                                    debugButtonStatus()
                                })
                            }
                        }
                    }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 1
                    color: "#e0e0e0"
                }
                
                // 地图缩放控制
                ColumnLayout {
                    spacing: 8
                    Layout.fillWidth: true
                    
                    Label {
                        text: "地图缩放"
                        font.pixelSize: 10
                        font.bold: true
                        color: "#34495e"
                    }
                    
                    // 缩放控制按钮（横向排列）
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 6
                        
                        Button {
                            text: "−−"
                            Layout.fillWidth: true
                            Layout.preferredHeight: 26
                            enabled: mapReady && getCurrentMap()
                            
                            background: Rectangle {
                                color: parent.enabled ? "#e74c3c" : "#ecf0f1"
                                radius: 4
                                border.color: parent.enabled ? "#c0392b" : "#bdc3c7"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                font.bold: true
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                var currentMap = getCurrentMap()
                                if (currentMap) {
                                    if (selectedMapType === 0) {
                                        // 高德地图模式
                                        if (currentMap.zoomOut) {
                                            currentMap.zoomOut()
                                        }
                                    } else {
                                        // 工作区地图模式
                                        if (currentMap.zoomOut) {
                                            currentMap.zoomOut(0.5)
                                        }
                                    }
                                }
                            }
                        }
                        
                        Button {
                            text: "−"
                            Layout.fillWidth: true
                            Layout.preferredHeight: 26
                            enabled: mapReady && getCurrentMap()
                            
                            background: Rectangle {
                                color: parent.enabled ? "#e67e22" : "#ecf0f1"
                                radius: 4
                                border.color: parent.enabled ? "#d35400" : "#bdc3c7"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                font.bold: true
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                var currentMap = getCurrentMap()
                                if (currentMap) {
                                    if (selectedMapType === 0) {
                                        // 高德地图模式
                                        if (currentMap.zoomOut) {
                                            currentMap.zoomOut()
                                        }
                                    } else {
                                        // 工作区地图模式
                                        if (currentMap.zoomOut) {
                                            currentMap.zoomOut(0.1)
                                        }
                                    }
                                }
                            }
                        }
                        
                        Button {
                            text: "100%"
                            Layout.fillWidth: true
                            Layout.preferredHeight: 26
                            enabled: mapReady && getCurrentMap()
                            
                            background: Rectangle {
                                color: parent.enabled ? "#3498db" : "#ecf0f1"
                                radius: 4
                                border.color: parent.enabled ? "#2980b9" : "#bdc3c7"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                font.bold: true
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                var currentMap = getCurrentMap()
                                if (currentMap) {
                                    if (selectedMapType === 0) {
                                        // 高德地图模式
                                        if (currentMap.setZoomLevel) {
                                            currentMap.setZoomLevel(16)
                                        }
                                    } else {
                                        // 工作区地图模式
                                        if (currentMap.setScale) {
                                            currentMap.setScale(1.0)
                                        }
                                    }
                                }
                            }
                        }
                        
                        Button {
                            text: "+"
                            Layout.fillWidth: true
                            Layout.preferredHeight: 26
                            enabled: mapReady && getCurrentMap()
                            
                            background: Rectangle {
                                color: parent.enabled ? "#e67e22" : "#ecf0f1"
                                radius: 4
                                border.color: parent.enabled ? "#d35400" : "#bdc3c7"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                font.bold: true
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                var currentMap = getCurrentMap()
                                if (currentMap) {
                                    if (selectedMapType === 0) {
                                        // 高德地图模式
                                        if (currentMap.zoomIn) {
                                            currentMap.zoomIn()
                                        }
                                    } else {
                                        // 工作区地图模式
                                        if (currentMap.zoomIn) {
                                            currentMap.zoomIn(0.1)
                                        }
                                    }
                                }
                            }
                        }
                        
                        Button {
                            text: "++"
                            Layout.fillWidth: true
                            Layout.preferredHeight: 26
                            enabled: mapReady && getCurrentMap()
                            
                            background: Rectangle {
                                color: parent.enabled ? "#e74c3c" : "#ecf0f1"
                                radius: 4
                                border.color: parent.enabled ? "#c0392b" : "#bdc3c7"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                font.bold: true
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                var currentMap = getCurrentMap()
                                if (currentMap) {
                                    if (selectedMapType === 0) {
                                        // 高德地图模式
                                        if (currentMap.zoomIn) {
                                            currentMap.zoomIn()
                                        }
                                    } else {
                                        // 工作区地图模式
                                        if (currentMap.zoomIn) {
                                            currentMap.zoomIn(0.5)
                                        }
                                    }
                                }
                            }
                        }
                    }
                    
                    // 适应窗口按钮
                    Button {
                        text: "适应窗口"
                        Layout.fillWidth: true
                        Layout.preferredHeight: 26
                        enabled: mapReady && getCurrentMap()
                        
                        background: Rectangle {
                            color: parent.enabled ? "#27ae60" : "#ecf0f1"
                            radius: 4
                            border.color: parent.enabled ? "#229954" : "#bdc3c7"
                            border.width: 1
                        }
                        
                        contentItem: Text {
                            text: parent.text
                            color: parent.enabled ? "white" : "#95a5a6"
                            font.pixelSize: 10
                            font.bold: true
                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                        }
                        
                        onClicked: {
                            var currentMap = getCurrentMap()
                            if (currentMap) {
                                if (selectedMapType === 0) {
                                    // 高德地图模式
                                    if (currentMap.resetView) {
                                        currentMap.resetView()
                                    }
                                } else {
                                    // 工作区地图模式
                                    if (currentMap.autoFitToWindow) {
                                        currentMap.autoFitToWindow()
                                    }
                                }
                            }
                        }
                    }
                    
                    // 当前缩放比例显示
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: 24
                        color: "#f8f9fa"
                        radius: 4
                        border.color: "#dee2e6"
                        border.width: 1
                        
                        Text {
                            anchors.centerIn: parent
                            text: "当前缩放: " + (function() {
                                var currentMap = getCurrentMap()
                                if (currentMap) {
                                    if (selectedMapType === 0) {
                                        // 高德地图模式
                                        if (currentMap.zoomLevel) {
                                            return "级别 " + currentMap.zoomLevel
                                        }
                                    } else {
                                        // 工作区地图模式
                                        if (currentMap.currentScale) {
                                            return (currentMap.currentScale * 100).toFixed(0) + "%"
                                        }
                                    }
                                }
                                return "100%"
                            })()
                            font.pixelSize: 10
                            color: "#495057"
                            font.bold: true
                        }
                    }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 1
                    color: "#e0e0e0"
                }
                
                // 农田规划控制
                ColumnLayout {
                    spacing: 8
                    Layout.fillWidth: true
                    
                    Label {
                        text: "农田规划"
                        font.pixelSize: 10
                        font.bold: true
                        color: "#34495e"
                    }
                    
                    // 农田规划按钮（居中显示）
                    Button {
                        text: fieldPlanMode ? "退出规划" : "农田规划"
                        Layout.fillWidth: true
                        Layout.preferredHeight: 30
                        enabled: mapReady
                        
                        background: Rectangle {
                            color: parent.enabled ? (fieldPlanMode ? "#9c27b0" : "#ff9800") : "#ecf0f1"
                            radius: 4
                            border.color: parent.enabled ? (fieldPlanMode ? "#7b1fa2" : "#f57c00") : "#bdc3c7"
                            border.width: 1
                        }
                        
                        contentItem: Text {
                            text: parent.text
                            color: parent.enabled ? "white" : "#95a5a6"
                            font.pixelSize: 10
                            font.bold: true
                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                        }
                        
                        onClicked: {
                            var currentMap = getCurrentMap()
                            if (currentMap) {
                                currentMap.toggleFieldPlanMode()
                                fieldPlanMode = currentMap.fieldPlanMode
                                
                                // 强制刷新按钮状态
                                Qt.callLater(function() {
                                    debugButtonStatus()
                                })
                            }
                        }
                    }
                    
                    // 保存和加载按钮（横向排列）
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 6
                        Button {
                            text: "保存农田"
                            Layout.fillWidth: true
                            Layout.preferredHeight: 26
                            enabled: {
                                // 修复：简化启用条件，只要地图就绪且有农田点即可
                                var currentMap = getCurrentMap()
                                return mapReady && currentMap && currentMap.fieldPointsModel && currentMap.fieldPointsModel.count >= 3
                            }
                            
                            background: Rectangle {
                                color: parent.enabled ? "#4caf50" : "#ecf0f1"
                                radius: 4
                                border.color: parent.enabled ? "#45a049" : "#bdc3c7"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                saveFieldPlan()
                            }
                        }
                        
                        Button {
                            text: "加载农田"
                            Layout.fillWidth: true
                            Layout.preferredHeight: 26
                            enabled: mapReady
                            
                            background: Rectangle {
                                color: parent.enabled ? "#2196f3" : "#ecf0f1"
                                radius: 4
                                border.color: parent.enabled ? "#1976d2" : "#bdc3c7"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                loadFieldPlan()
                            }
                        }
                    }
                    
                    // 清除农田按钮
                    Button {
                        text: "清除农田"
                        Layout.fillWidth: true
                        Layout.preferredHeight: 26
                        enabled: {
                            // 修复：简化启用条件，只要地图就绪且有农田点即可
                            var currentMap = getCurrentMap()
                            return mapReady && currentMap && currentMap.fieldPointsModel && currentMap.fieldPointsModel.count > 0
                        }
                        
                        background: Rectangle {
                            color: parent.enabled ? "#e91e63" : "#ecf0f1"
                            radius: 4
                            border.color: parent.enabled ? "#c2185b" : "#bdc3c7"
                            border.width: 1
                        }
                        
                        contentItem: Text {
                            text: parent.text
                            color: parent.enabled ? "white" : "#95a5a6"
                            font.pixelSize: 10
                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                        }
                        
                        onClicked: {
                            var currentMap = getCurrentMap()
                            if (currentMap) {
                                currentMap.clearFieldPlan()
                                fieldPlanMode = false
                            }
                        }
                    }
                    
                    // 农田面积显示
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: fieldInfoColumn.height + 16
                        color: "#fff3e0"
                        radius: 4
                        border.color: "#ff9800"
                        border.width: 1
                        visible: {
                            var currentMap = getCurrentMap()
                            return currentMap && currentMap.fieldPointsModel && currentMap.fieldPointsModel.count >= 3
                        }
                        
                        Column {
                            id: fieldInfoColumn
                            anchors.fill: parent
                            anchors.margins: 8
                            spacing: 6
                            
                            Text {
                                text: "规划点数: " + (function() {
                                    var currentMap = getCurrentMap()
                                    return currentMap && currentMap.fieldPointsModel ? currentMap.fieldPointsModel.count : 0
                                })()
                                font.pixelSize: 10
                                color: "#e65100"
                            }
                            
                            Text {
                                text: "农田面积: " + (function() {
                                    var currentMap = getCurrentMap()
                                    return currentMap && currentMap.calculateFieldArea ? currentMap.calculateFieldArea().toFixed(2) : "0.00"
                                })() + " 亩"
                                font.pixelSize: 10
                                color: "#e65100"
                                font.bold: true
                            }
                        }
                    }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 1
                    color: "#e0e0e0"
                }
                
                // 路径编辑控制
                ColumnLayout {
                    spacing: 8
                    Layout.fillWidth: true
                    
                    Label {
                        text: "路径编辑"
                        font.pixelSize: 10
                        font.bold: true
                        color: "#34495e"
                    }
                    
                    Button {
                        text: pathEditMode ? "退出编辑" : "编辑路径"
                        Layout.fillWidth: true
                        Layout.preferredHeight: 30
                        enabled: mapReady
                        
                        background: Rectangle {
                            color: parent.enabled ? (pathEditMode ? "#e74c3c" : "#27ae60") : "#ecf0f1"
                            radius: 4
                            border.color: parent.enabled ? (pathEditMode ? "#c0392b" : "#229954") : "#bdc3c7"
                            border.width: 1
                        }
                        
                        contentItem: Text {
                            text: parent.text
                            color: parent.enabled ? "white" : "#95a5a6"
                            font.pixelSize: 10
                            font.bold: true
                            horizontalAlignment: Text.AlignHCenter
                            verticalAlignment: Text.AlignVCenter
                        }
                        
                        onClicked: {
                            var currentMap = getCurrentMap()
                            if (currentMap) {
                                currentMap.togglePathEditMode()
                                pathEditMode = currentMap.pathEditMode
                                
                                // 强制刷新按钮状态
                                Qt.callLater(function() {
                                    debugButtonStatus()
                                })
                            }
                        }
                    }
                    
                    // 保存路径和清除路径按钮（横向并排）
                    RowLayout {
                        Layout.fillWidth: true
                        spacing: 6
                        
                        Button {
                            text: "保存路径"
                            Layout.fillWidth: true
                            Layout.preferredHeight: 26
                            enabled: {
                                // 只要地图就绪且有路径点即可保存
                                var currentMap = getCurrentMap()
                                return mapReady && currentMap && currentMap.pathPointsModel && currentMap.pathPointsModel.count >= 2
                            }
                            
                            background: Rectangle {
                                color: parent.enabled ? "#4caf50" : "#ecf0f1"
                                radius: 4
                                border.color: parent.enabled ? "#45a049" : "#bdc3c7"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                savePath()
                            }
                        }
                        
                        Button {
                            text: "清除路径"
                            Layout.fillWidth: true
                            Layout.preferredHeight: 26
                            enabled: {
                                // 修复：简化启用条件，只要地图就绪且有路径点即可
                                var currentMap = getCurrentMap()
                                return mapReady && currentMap && currentMap.pathPointsModel && currentMap.pathPointsModel.count > 0
                            }
                            
                            background: Rectangle {
                                color: parent.enabled ? "#f39c12" : "#ecf0f1"
                                radius: 4
                                border.color: parent.enabled ? "#e67e22" : "#bdc3c7"
                                border.width: 1
                            }
                            
                            contentItem: Text {
                                text: parent.text
                                color: parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                horizontalAlignment: Text.AlignHCenter
                                verticalAlignment: Text.AlignVCenter
                            }
                            
                            onClicked: {
                                var currentMap = getCurrentMap()
                                if (currentMap) {
                                    currentMap.clearPath()
                                    // 清除路径后重置距离
                                    routeDistance = 0.0
                                    routeDuration = 0.0
                                }
                            }
                        }
                    }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 1
                    color: "#e0e0e0"
                }
                
                // 路线规划控制
                ColumnLayout {
                    spacing: 8
                    Layout.fillWidth: true
                    
                    Label {
                        text: "路线规划"
                        font.pixelSize: 10
                        font.bold: true
                        color: "#34495e"
                    }
                    
                    // 路线服务提供商选择
                    ComboBox {
                        id: providerCombo
                        Layout.fillWidth: true
                        model: savedPathsModel
                        textRole: "text"
                        currentIndex: 0
                        
                        onActivated: {
                            var selectedItem = model[index]
                            routeProvider = selectedItem.value
                            
                            // 如果是保存的路径（value以"saved_path_"开头），则加载该路径
                            if (routeProvider && routeProvider.indexOf("saved_path_") === 0) {
                                loadSavedPath(routeProvider)
                            } else {
                                // 否则使用路线服务提供商
                                if (routeService) {
                                    routeService.setRouteProvider(routeProvider)
                                }
                            }
                            console.log("路线服务切换到:", routeProvider)
                        }
                    }
                    
                    Button {
                        text: isPlanning ? "规划中..." : "任务下发"
                        Layout.fillWidth: true
                        Layout.preferredHeight: 30
                        enabled: {
                            var currentMap = getCurrentMap()
                            return mapReady && currentMap && currentMap.pathPointsModel && currentMap.pathPointsModel.count >= 2 && !isPlanning
                        }
                        
                        background: Rectangle {
                            color: parent.enabled ? "#3498db" : "#ecf0f1"
                            radius: 4
                            border.color: parent.enabled ? "#2980b9" : "#bdc3c7"
                            border.width: 1
                        }
                        
                        contentItem: Row {
                            anchors.centerIn: parent
                            spacing: 8
                            
                            BusyIndicator {
                                running: isPlanning
                                visible: isPlanning
                                width: 18
                                height: 18
                                anchors.verticalCenter: parent.verticalCenter
                            }
                            
                            Text {
                                text: parent.parent.text
                                color: parent.parent.enabled ? "white" : "#95a5a6"
                                font.pixelSize: 10
                                font.bold: true
                                anchors.verticalCenter: parent.verticalCenter
                            }
                        }
                        
                        onClicked: {
                            sendTaskToRobot()
                        }
                    }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 1
                    color: "#e0e0e0"
                }
                
                // 路径统计信息
                ColumnLayout {
                    spacing: 8
                    Layout.fillWidth: true
                    
                    Label {
                        text: "路径统计"
                        font.pixelSize: 10
                        font.bold: true
                        color: "#34495e"
                    }
                    
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: pathStatsColumn.height + 16
                        color: "#f8f9fa"
                        radius: 4
                        border.color: "#dee2e6"
                        border.width: 1
                        
                        Column {
                            id: pathStatsColumn
                            anchors.fill: parent
                            anchors.margins: 8
                            spacing: 6
                            
                            Text {
                                text: "路径点数: " + (function() {
                                    var currentMap = getCurrentMap()
                                    return mapReady && currentMap && currentMap.pathPointsModel ? currentMap.pathPointsModel.count : 0
                                })()
                                font.pixelSize: 10
                                color: "#495057"
                            }
                            
                            Text {
                                text: "路径距离: " + (function() {
                                    // 优先显示计算出的路径距离
                                    var calculatedDistance = calculatePathDistance()
                                    if (calculatedDistance > 0) {
                                        if (calculatedDistance < 1000) {
                                            return calculatedDistance.toFixed(1) + " 米"
                                        } else {
                                            return (calculatedDistance / 1000).toFixed(2) + " 公里"
                                        }
                                    }
                                    // 如果没有路径点，显示规划距离（如果有）
                                    if (routeDistance > 0) {
                                        if (routeDistance < 1000) {
                                            return routeDistance.toFixed(1) + " 米"
                                        } else {
                                            return (routeDistance / 1000).toFixed(2) + " 公里"
                                        }
                                    }
                                    return "未规划"
                                })()
                                font.pixelSize: 10
                                color: (calculatePathDistance() > 0 || routeDistance > 0) ? "#27ae60" : "#95a5a6"
                                font.bold: (calculatePathDistance() > 0 || routeDistance > 0)
                            }
                            
                            Text {
                                text: "预计时长: " + (function() {
                                    if (routeDuration > 0) {
                                        var minutes = Math.floor(routeDuration / 60)
                                        var seconds = Math.floor(routeDuration % 60)
                                        if (minutes > 0) {
                                            return minutes + "分" + seconds + "秒"
                                        } else {
                                            return seconds + "秒"
                                        }
                                    }
                                    return "未规划"
                                })()
                                font.pixelSize: 10
                                color: routeDuration > 0 ? "#3498db" : "#95a5a6"
                                visible: routeDuration > 0
                            }
                            
                            Text {
                                text: "地图模式: " + (selectedMapType === 0 ? "高德地图" : "工作区")
                                font.pixelSize: 10
                                color: "#495057"
                            }
                        }
                    }
                }
                
                Rectangle {
                    Layout.fillWidth: true
                    Layout.preferredHeight: 1
                    color: "#e0e0e0"
                }
                
                // 机器人位置
                ColumnLayout {
                    spacing: 8
                    Layout.fillWidth: true
                    
                    Label {
                        text: "机器人位置"
                        font.pixelSize: 10
                        font.bold: true
                        color: "#34495e"
                    }
                    
                    Rectangle {
                        Layout.fillWidth: true
                        Layout.preferredHeight: robotStatsText.height + 16
                        color: "#e8f5e8"
                        radius: 4
                        border.color: "#27ae60"
                        border.width: 1
                        
                        Text {
                            id: robotStatsText
                            anchors.left: parent.left
                            anchors.top: parent.top
                            anchors.margins: 8
                            text: "在线机器人数量: " + (function() {
                                var currentMap = getCurrentMap()
                                return mapReady && currentMap && currentMap.robotPositionsModel ? currentMap.robotPositionsModel.count : 0
                            })() + " 台"
                            font.pixelSize: 10
                            color: "#27ae60"
                            font.bold: true
                        }
                    }
                }
                
                Item {
                    Layout.fillHeight: true
                }
            }
        }
    }
    
    // ==================== 顶部状态栏 ====================
    
    /*
    Rectangle {
        id: topStatusBar
        anchors.top: parent.top
        anchors.left: leftControlPanel.right
        anchors.right: parent.right
        anchors.margins: 16
        anchors.leftMargin: 32
        height: 60
        color: "white"
        radius: 8
        opacity: 0.95
        z: 100
        
        layer.enabled: true
        layer.effect: DropShadow {
            horizontalOffset: 0
            verticalOffset: 2
            radius: 12
            samples: 24
            color: "#40000000"
        }
        
        RowLayout {
            anchors.fill: parent
            anchors.margins: 12
            spacing: 16
            
            Item {
                Layout.fillWidth: true
            }
        }
    }
    */
    
    // ==================== 加载提示 ====================
    // 暂时不需要地图加载提示，已注释
    
    /*
    Rectangle {
        anchors.fill: parent
        color: "#cc000000"
        visible: mapLoading
        z: 500
        
        Column {
            anchors.centerIn: parent
            spacing: 20
            
            BusyIndicator {
                running: mapLoading
                width: 80
                height: 80
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Label {
                text: "正在加载地图..."
                font.pixelSize: 20
                font.bold: true
                color: "white"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            Label {
                text: selectedMapType === 0 ? "加载瓦片地图服务..." : "加载离线地图数据..."
                font.pixelSize: 12
                color: "#bdc3c7"
                anchors.horizontalCenter: parent.horizontalCenter
            }
        }
    }
    */
    
    // ==================== JavaScript函数 ====================
    
    function getCurrentMap() {
        if (selectedMapType === 0) {
            // 高德地图通过Loader加载
            if (gaodeMapLoader.status === Loader.Ready && gaodeMapLoader.item) {
                console.log("✅ 返回高德地图实例")
                return gaodeMapLoader.item
            }
            console.log("⚠️ 高德地图未就绪，Loader状态:", gaodeMapLoader.status)
            return null
        } else {
            // 工作区地图（离线地图）
            console.log("🔍 检查工作区地图状态:")
            console.log("- offlineMap存在:", !!offlineMap)
            console.log("- imageLoaded:", offlineMap ? offlineMap.imageLoaded : "undefined")
            console.log("- mapReady:", mapReady)
            
            if (offlineMap) {
                // 修复：只要offlineMap组件存在且mapReady为true，就返回地图实例
                // 不再严格依赖imageLoaded属性，因为地图组件可能已经可用
                if (mapReady) {
                    console.log("✅ 返回工作区地图实例 (mapReady=true)")
                    return offlineMap
                }
                // 如果mapReady为false但imageLoaded为true，也返回地图实例
                else if (offlineMap.imageLoaded) {
                    console.log("✅ 返回工作区地图实例 (imageLoaded=true)")
                    return offlineMap
                } else {
                    console.log("⚠️ 工作区地图未加载完成 (imageLoaded=false, mapReady=false)")
                }
            } else {
                console.log("⚠️ offlineMap组件不存在")
            }
            return null
        }
    }
    
    // 调试函数：检查按钮状态
    function debugButtonStatus() {
        console.log("=== 按钮状态调试 ===")
        console.log("selectedMapType:", selectedMapType)
        console.log("mapReady:", mapReady)
        
        var currentMap = getCurrentMap()
        console.log("getCurrentMap()结果:", !!currentMap)
        
        if (currentMap) {
            console.log("农田点数量:", currentMap.fieldPointsModel ? currentMap.fieldPointsModel.count : "undefined")
            console.log("路径点数量:", currentMap.pathPointsModel ? currentMap.pathPointsModel.count : "undefined")
            
            // 检查按钮启用条件
            var saveFieldEnabled = mapReady && currentMap && currentMap.fieldPointsModel && currentMap.fieldPointsModel.count >= 3
            var clearFieldEnabled = mapReady && currentMap && currentMap.fieldPointsModel && currentMap.fieldPointsModel.count > 0
            var clearPathEnabled = mapReady && currentMap && currentMap.pathPointsModel && currentMap.pathPointsModel.count > 0
            
            console.log("保存农田按钮启用:", saveFieldEnabled)
            console.log("清除农田按钮启用:", clearFieldEnabled)
            console.log("清除路径按钮启用:", clearPathEnabled)
        }
        console.log("==================")
    }
    
    function planRoute() {
        if (!routeService) {
            console.error("RouteService未初始化")
            return
        }
        
        var currentMap = getCurrentMap()
        if (!currentMap) {
            console.error("地图未加载")
            return
        }
        
        if (!currentMap.pathPointsModel || currentMap.pathPointsModel.count < 2) {
            console.warn("至少需要2个路径点才能规划路线")
            return
        }
        
        isPlanning = true
        
        // 构建路径点列表
        var waypoints = []
        for (var i = 0; i < currentMap.pathPointsModel.count; i++) {
            var point = currentMap.pathPointsModel.get(i)
            waypoints.push({
                lon: point.lon,
                lat: point.lat
            })
        }
        
        console.log("开始路线规划，路径点数:", waypoints.length, "提供商:", routeProvider)
        routeService.requestRoute(waypoints)
    }
    
    // 任务下发：发送路径跟踪指令给机器人
    function sendTaskToRobot() {
        if (!robotManager) {
            console.error("RobotManager未初始化")
            return
        }
        
        // 获取当前机器人（从父组件main.qml获取）
        var robotSN = null
        try {
            // 尝试从父组件获取currentRobot
            var parentItem = parent
            while (parentItem) {
                if (parentItem.currentRobot) {
                    robotSN = parentItem.currentRobot
                    break
                }
                parentItem = parentItem.parent
            }
        } catch (e) {
            console.warn("无法从父组件获取currentRobot:", e)
        }
        
        if (!robotSN) {
            console.error("无法获取当前机器人，请先选择机器人")
            return
        }
        
        var currentMap = getCurrentMap()
        if (!currentMap) {
            console.error("地图未加载")
            return
        }
        
        // 获取路径点
        var pathPoints = []
        
        // 检查是否选择了保存的路径
        if (routeProvider && routeProvider.indexOf("saved_path_") === 0) {
            // 从保存的路径数据中获取
            var pathData = savedPathsDataStorage.getPathData(routeProvider)
            if (pathData && pathData.points) {
                pathPoints = pathData.points
                console.log("使用保存的路径:", pathData.name, "路径点数:", pathPoints.length)
            } else {
                console.error("保存的路径数据不存在:", routeProvider)
                return
            }
        } else {
            // 从地图获取路径点（优先使用规划后的路径，否则使用用户点击的路径点）
            if (currentMap.routePathModel && currentMap.routePathModel.count >= 2) {
                // 使用规划后的路径
                for (var i = 0; i < currentMap.routePathModel.count; i++) {
                    var point = currentMap.routePathModel.get(i)
                    pathPoints.push({
                        lon: point.lon,
                        lat: point.lat
                    })
                }
                console.log("使用规划后的路径，路径点数:", pathPoints.length)
            } else if (currentMap.pathPointsModel && currentMap.pathPointsModel.count >= 2) {
                // 使用用户点击的路径点
                for (var i = 0; i < currentMap.pathPointsModel.count; i++) {
                    var point = currentMap.pathPointsModel.get(i)
                    pathPoints.push({
                        lon: point.lon,
                        lat: point.lat
                    })
                }
                console.log("使用用户点击的路径点，路径点数:", pathPoints.length)
            } else {
                console.error("路径点数量不足，至少需要2个点")
                return
            }
        }
        
        if (pathPoints.length < 2) {
            console.error("路径点数量不足，至少需要2个点")
            return
        }
        
        // 调用RobotManager开始路径跟踪（固定速度20）
        var success = robotManager.startPathTracking(robotSN, pathPoints, 20)
        
        if (success) {
            console.log("✅ 任务下发成功！机器人:", robotSN, "路径点数:", pathPoints.length)
        } else {
            console.error("❌ 任务下发失败！机器人:", robotSN)
        }
    }
    
    // 保存农田规划
    function saveFieldPlan() {
        var currentMap = getCurrentMap()
        if (!currentMap || !currentMap.fieldPointsModel || currentMap.fieldPointsModel.count < 3) {
            console.warn("无法保存：农田点数不足3个")
            return
        }
        
        var fieldData = {
            name: "农田_" + new Date().toISOString().slice(0, 10),
            date: new Date().toISOString(),
            points: []
        }
        
        for (var i = 0; i < currentMap.fieldPointsModel.count; i++) {
            var point = currentMap.fieldPointsModel.get(i)
            fieldData.points.push({
                lon: point.lon,
                lat: point.lat
            })
        }
        
        var jsonData = JSON.stringify(fieldData, null, 2)
        console.log("保存农田规划:", jsonData)
        
        // 存储到localStorage
        var storageKey = "fieldPlan_" + fieldData.name
        try {
            // 注意：QML的localStorage需要Qt.labs.platform import
            console.log("农田规划已保存到:", storageKey)
            
            // 标记农田为已保存状态
            if (currentMap.markFieldPlanAsSaved) {
                currentMap.markFieldPlanAsSaved()
            }
            
            // 提示保存成功
            console.log("✅ 农田规划保存成功！农田面积:", currentMap.calculateFieldArea().toFixed(2), "亩")
        } catch (e) {
            console.error("保存失败:", e)
        }
    }
    
    // 加载农田规划
    function loadFieldPlan() {
        var currentMap = getCurrentMap()
        if (!currentMap) {
            console.error("地图未加载")
            return
        }
        
        // 从localStorage加载
        try {
            console.log("加载农田规划...")
            
            // 示例：创建一个测试农田区域
            var testField = {
                name: "示例农田",
                points: [
                    {lon: 109.240, lat: 23.724},
                    {lon: 109.245, lat: 23.724},
                    {lon: 109.245, lat: 23.730},
                    {lon: 109.240, lat: 23.730}
                ]
            }
            
            // 加载到地图
            currentMap.loadFieldPlan(testField.points)
            console.log("✅ 农田规划加载成功！")
        } catch (e) {
            console.error("加载失败:", e)
        }
    }
    
    // 保存路径
    function savePath() {
        var currentMap = getCurrentMap()
        if (!currentMap || !currentMap.pathPointsModel || currentMap.pathPointsModel.count < 2) {
            console.warn("无法保存：路径点数不足2个")
            return
        }
        
        // 生成系统命名：路径_日期_时间
        var now = new Date()
        var dateStr = now.toISOString().slice(0, 10).replace(/-/g, "")
        var timeStr = now.toTimeString().slice(0, 8).replace(/:/g, "")
        var pathName = "路径_" + dateStr + "_" + timeStr
        var pathValue = "saved_path_" + dateStr + "_" + timeStr
        
        // 构建路径点数据
        var pathPoints = []
        for (var i = 0; i < currentMap.pathPointsModel.count; i++) {
            var point = currentMap.pathPointsModel.get(i)
            pathPoints.push({
                lon: point.lon,
                lat: point.lat
            })
        }
        
        // 保存路径数据
        savedPathsDataStorage.setPathData(pathValue, {
            name: pathName,
            points: pathPoints,
            savedTime: now.toISOString()
        })
        
        // 添加到下拉框model（插入到"直线规划"之后）
        var newModel = savedPathsModel.slice() // 复制数组
        newModel.splice(1, 0, {text: pathName, value: pathValue}) // 在索引1位置插入
        savedPathsModel = newModel
        
        console.log("✅ 路径保存成功！名称:", pathName, "路径点数:", pathPoints.length)
    }
    
    // 计算路径点总距离（使用Haversine公式）
    function calculatePathDistance() {
        var currentMap = getCurrentMap()
        if (!currentMap || !currentMap.pathPointsModel || currentMap.pathPointsModel.count < 2) {
            return 0.0
        }
        
        var totalDistance = 0.0
        var R = 6371000.0  // 地球半径（米）
        
        for (var i = 0; i < currentMap.pathPointsModel.count - 1; i++) {
            var point1 = currentMap.pathPointsModel.get(i)
            var point2 = currentMap.pathPointsModel.get(i + 1)
            
            var lat1 = point1.lat * Math.PI / 180.0
            var lat2 = point2.lat * Math.PI / 180.0
            var dLat = (point2.lat - point1.lat) * Math.PI / 180.0
            var dLon = (point2.lon - point1.lon) * Math.PI / 180.0
            
            var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                    Math.cos(lat1) * Math.cos(lat2) *
                    Math.sin(dLon / 2) * Math.sin(dLon / 2)
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
            
            totalDistance += R * c
        }
        
        return totalDistance
    }
    
    // 更新路径距离（在路径点变化时调用）
    function updatePathDistance() {
        var distance = calculatePathDistance()
        // 如果计算出的距离大于0，更新显示
        // 注意：这里不直接更新routeDistance，因为routeDistance是规划后的距离
        // 我们通过calculatePathDistance()函数实时计算显示
        console.log("路径距离已更新:", distance.toFixed(2), "米")
    }
    
    // 加载保存的路径
    function loadSavedPath(pathValue) {
        var currentMap = getCurrentMap()
        if (!currentMap) {
            console.error("地图未加载")
            return
        }
        
        var pathData = savedPathsDataStorage.getPathData(pathValue)
        if (!pathData) {
            console.error("路径数据不存在:", pathValue)
            return
        }
        console.log("加载保存的路径:", pathData.name, "路径点数:", pathData.points.length)
        
        // 清除当前路径
        if (currentMap.clearPath) {
            currentMap.clearPath()
        }
        
        // 加载保存的路径点
        if (currentMap.setPathPoints && pathData.points) {
            currentMap.setPathPoints(pathData.points)
            console.log("✅ 路径加载成功！")
            // 加载后更新距离
            Qt.callLater(function() {
                updatePathDistance()
            })
        } else if (currentMap.addPathPoint && pathData.points) {
            // 如果setPathPoints方法不存在，尝试逐个添加点
            for (var i = 0; i < pathData.points.length; i++) {
                var point = pathData.points[i]
                currentMap.addPathPoint(point.lon, point.lat)
            }
            console.log("✅ 路径加载成功（逐个添加）！")
            // 加载后更新距离
            Qt.callLater(function() {
                updatePathDistance()
            })
        } else {
            console.warn("无法加载路径：地图组件不支持路径点设置方法")
        }
    }
    
    // ==================== 组件初始化 ====================
    
    Component.onCompleted: {
        console.log("GIS页面初始化 - 全屏地图模式")
        
        // 连接RouteService信号
        if (routeService) {
            routeService.routeReady.connect(function(path, distance, duration) {
                console.log("路线规划完成，路径点数:", path.length, "距离:", distance, "米", "时长:", duration, "秒")
                isPlanning = false
                
                // 更新路径距离和时长
                routeDistance = distance
                routeDuration = duration
                
                // 将规划路线显示到地图上
                var currentMap = getCurrentMap()
                if (currentMap) {
                    if (currentMap.setRoutePathFromService) {
                        currentMap.setRoutePathFromService(path)
                    } else if (currentMap.setRoutePath) {
                        currentMap.setRoutePath(path)
                    }
                }
            })
            
            routeService.routeError.connect(function(error) {
                console.error("路线规划错误:", error)
                isPlanning = false
                // 清除路径距离显示
                routeDistance = 0.0
                routeDuration = 0.0
            })
            
            routeService.routeProgress.connect(function(percentage) {
                console.log("路线规划进度:", percentage + "%")
            })
            
            console.log("已连接RouteService信号")
        } else {
            console.warn("RouteService未找到")
        }
        
        // 连接机器人实时定位信号
        if (robotManager) {
            robotManager.robotLocationUpdated.connect(function(sn, longitude, latitude) {
                console.log("接收到机器人实时定位更新:", sn, longitude, latitude)
                var currentMap = getCurrentMap()
                if (currentMap) {
                    currentMap.updateRobotPosition(sn, longitude, latitude, "在线")
                }
            })
            console.log("已连接机器人实时定位信号")
            
            // 连接路径跟踪信号
            robotManager.pathTrackingCompleted.connect(function(sn) {
                console.log("✅ 路径跟踪完成:", sn)
                // 可以在这里显示完成提示
            })
            
            robotManager.pathTrackingError.connect(function(sn, error) {
                console.error("❌ 路径跟踪错误:", sn, error)
                // 可以在这里显示错误提示
            })
            
            robotManager.pathTrackingProgress.connect(function(sn, currentIndex, totalPoints, distanceToTarget) {
                var progress = ((currentIndex + 1) / totalPoints * 100).toFixed(1)
                console.log("路径跟踪进度:", sn, progress + "%", "距离目标:", distanceToTarget.toFixed(2), "米")
            })
            
            console.log("已连接路径跟踪信号")
        } else {
            console.warn("robotManager未找到")
        }
        
        // 延迟调试按钮状态
        Qt.callLater(function() {
            debugButtonStatus()
        })
    }
}
